package login.controller;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import login.client.CacheClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author 江江
 * @Date 2020/7/29 15:45
 *
 * 0730 -- http://www.openapi.sys/openapi?method=order.out&userName=admin&appkey=msmsms23330&password=admin&fwcsgl=qq
 */
@RestController
public class LoginController {
    @Autowired
    private CacheClient cacheClient;

    @RequestMapping("/login")
    public String login(String userName, String password, String appkey) {
        if ("admin".equals(userName) && "admin".equals(password)) {
            Date date = new Date();
            JwtBuilder builder = Jwts.builder()
                    .setSubject("loginhehe")//告诉签名当前是谁
                    .signWith(SignatureAlgorithm.HS256,"shayebuzhidao")

                    .setIssuedAt(date)//开始时间
                    .setExpiration(new Date(date.getTime()+3600000))//结束时间
                    .claim("id","1000")
                    .claim("userName",userName)
                    .claim("passWord",password);
            String jwt = builder.compact();//生成签名字符串
            System.err.println(jwt);
           // response.setHeader("compace_token",jwt);
            try {
                cacheClient.save2Redis("compace_token"+appkey,jwt,-1l);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "{\"userName\":\"" + userName + "\",\"password\":\"" + password + "\"}";
        }
        return "{\"error\":\"登录失败\"}";
    }
}
